package cn.yuhao.party.file.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.yuhao.party.file.domain.FileDomain;
import cn.yuhao.party.pager.PageBean;
import cn.yuhao.party.pager.PageConstants;

public class FileDao {
	private QueryRunner qr=new TxQueryRunner();

	public void addFile(FileDomain file) {
		String sql="insert into file values(?,?,?)";
		Object[] params={file.getName(),file.getFile(),file.getDate()};
		try {
			qr.update(sql,params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public PageBean<FileDomain> findAll(int pc) {
		int ps = PageConstants.BOOK_PAGE_SIZE;//每页记录数
		String sql = "select * from file order by date desc limit ?,?";
		try {
			String sql1 = "select count(*) from file";
			Number number = (Number)qr.query(sql1, new ScalarHandler());
			int tr = number.intValue();//得到了总记录数
			List<FileDomain> listnews = qr.query(sql, new BeanListHandler<FileDomain>(
					FileDomain.class),(pc-1) * ps,ps);
			PageBean<FileDomain> pb = new PageBean<FileDomain>();
			/*
			 * 其中PageBean没有url，这个任务由Servlet完成
			 */
			pb.setBeanList(listnews);
			pb.setPc(pc);
			pb.setPs(ps);
			pb.setTr(tr);
			
			return pb;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void delete(String file) throws SQLException {
		String sql="delete from file where file=?";
		System.out.println("文件删除dao"+file);
		qr.update(sql,file);
	}
}
